package com.adun.scheduler.controller;

import com.adun.scheduler.ISchedulerJob;
import com.adun.scheduler.common.AmisResult;
import com.adun.scheduler.context.SchedulerJobLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.config.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author ZDF
 * @date 2025/8/15
 */
@Slf4j
@RestController
@RequestMapping("/dynamic/scheduler/job/local")
public class SchedulerJobLocalController {

    @GetMapping("/pause")
    public AmisResult<String> pause(@RequestParam(value = "jobName") String jobName) {
        if (!SchedulerJobLocalContext.existJobName(jobName)) {
            return AmisResult.fail("任务不存在");
        }
        SchedulerJobLocalContext.destroyJob(jobName);
        log.info("【任务暂停】:{}", jobName);
        return AmisResult.successMsg("暂停成功");
    }

    @GetMapping("/resume")
    public AmisResult<String> resume(@RequestParam(value = "jobName") String jobName) {
        ISchedulerJob schedulerJob = SchedulerJobLocalContext.getSchedulerJob(jobName);
        SchedulerJobLocalContext.registerJob(schedulerJob.getJobName(), schedulerJob);
        log.info("【任务恢复】:{}", jobName);
        return AmisResult.successMsg("恢复成功");
    }

    @GetMapping("/cron")
    public AmisResult<String> changeCron(@RequestParam(value = "jobName") String jobName, @RequestParam(value = "cron") String cron) {
        if (!SchedulerJobLocalContext.existJobName(jobName)) {
            return AmisResult.fail("任务不存在");
        }
        ISchedulerJob schedulerJob = SchedulerJobLocalContext.getSchedulerJob(jobName);
        log.info("【任务cron变更】:【历史表达式】:{}:【目标表达式】:{}",schedulerJob.getJobCron(), cron);
        schedulerJob.setJobCron(cron);
        SchedulerJobLocalContext.destroyJob(jobName);
        SchedulerJobLocalContext.registerJob(schedulerJob.getJobName(), schedulerJob, cron);
        return AmisResult.successMsg("变更成功");
    }

    /**
     * 立即执行一次对应任务
     */
    @GetMapping("/execute")
    public AmisResult<String> execute(@RequestParam(value = "jobName") String jobName) {
        if (!SchedulerJobLocalContext.existJobName(jobName)) {
            return AmisResult.fail("任务不存在");
        }
        ISchedulerJob schedulerJob = SchedulerJobLocalContext.getSchedulerJob(jobName);
        schedulerJob.execute();
        return AmisResult.successMsg("执行成功");
    }
}
